#!/usr/bin/env python

import os
import urllib
import subprocess
import re
import datetime

import feedparser

import subscriptions

def torrent_from_link(url):
    url = url.replace("tor","get")
    print "Downloading",url
    socket = urllib.urlopen(url)
    data = socket.read()
    socket.close()
    return data

def write_torrent(torrent, filename="default.torrent"):
    f = open(filename,"wb")
    f.write(torrent)
    f.close()
    return filename

def execute_torrent(filename):
    commandline = "open %s" % filename
    p = subprocess.Popen(commandline, shell=True)
    status = os.waitpid(p.pid, 0)
    return status
    
def filter_on_name(name,item):
    print name, item
    p = re.compile("^%s " % name, re.I)
    match = p.match(item)
    return match != None

if __name__=="__main__":
    print "awsome"
    subscriptions.load()
    for feed in subscriptions.subscriptions:
        print feed["name"]
        for url in feed["url"]:
            print url
            d = feedparser.parse(url)
            print "parsed"
            for item in d.entries:
                if feed["last_time"] < datetime.datetime(*item.updated_parsed[:6]) and filter_on_name(feed["name"], item.title):
                    execute_torrent(write_torrent(torrent_from_link(item.link)))
                    print feed["last_time"], item.updated_parsed
                    feed["last_time"] = datetime.datetime(*item.updated_parsed[:6])
    subscriptions.save()